package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.GoogleAuthenticator;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.entity.Button;
import com.antdesignbackend.backend.entity.Menu;
import com.antdesignbackend.backend.entity.UserRoles;
import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.entity.entityVo.RoleMenuVo;
import com.antdesignbackend.backend.entity.entityVo.UserRoleVo;
import com.antdesignbackend.backend.entity.entityVo.UsersVo;
import com.antdesignbackend.backend.mapper.RolesMapper;
import com.antdesignbackend.backend.service.PermissionService;
import com.antdesignbackend.backend.service.RoleMenuService;
import com.antdesignbackend.backend.service.UserRolesService;
import com.antdesignbackend.backend.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Controller
@RequestMapping("/UserManage")
public class UserController {
    @Autowired
    UserRolesService userRolesService;
    @Autowired
    PermissionService permissionService;
    @Autowired
    UserService userService;
    @Autowired
    RoleMenuService roleMenuService;
    @Autowired
    RolesMapper rolesMapper;


    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Integer menuId;


    @GetMapping("/index")
    @AuthToken
    public String buttonIndex(String menuId) {
        this.menuId = Integer.parseInt(menuId);
        return "user/index";
    }

    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody UserRoleVo userRoleVo) {
        ReturnVO result = new ReturnVO();
        List<UsersVo> datalist=new ArrayList<>();
        QueryWrapper<UsersVo> wrapper =new QueryWrapper<UsersVo>();
        //正常查询过滤条件
        if(userRoleVo.getUserName()!=null && !userRoleVo.getUserName().equals("")){
            wrapper.and(wra -> wra.like("userName", userRoleVo.getUserName()));
        }
        if(userRoleVo.getUserType()!=null && userRoleVo.getUserType()>= 0){
            wrapper.and(wra -> wra.eq("userType", userRoleVo.getUserType()));
        }
        if(userRoleVo.getActivity()!=null && userRoleVo.getActivity()>= 0){
            wrapper.and(wra -> wra.eq("activity", userRoleVo.getActivity()));
        }
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=userService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= userService.searchs(wrapper.orderByAsc("userName"),new Page<>(userRoleVo.getPageIndex(),userRoleVo.getPageSize()));
        }
        result.setData(datalist);
        return result;
    }
    /*@PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody UserRoleVo userRoleVo) {
        ReturnVO returnVO = new ReturnVO();
        try {
            QueryWrapper<UserRoleVo> queryWrapper = new QueryWrapper<>();
            if (userRoleVo.getUserName() != null && !userRoleVo.getUserName().equals(""))
                queryWrapper.eq("userName", userRoleVo.getUserName());
            if (userRoleVo.getUserType() != null && userRoleVo.getUserType() >= 0)
                queryWrapper.eq("userType", userRoleVo.getUserType());
            if (userRoleVo.getActivity() != null && userRoleVo.getActivity() >= 0)
                queryWrapper.eq("activity", userRoleVo.getActivity());
            int total = userRolesService.count(queryWrapper);

            if (userRoleVo.getSort() != null && !userRoleVo.getSort().equals("")) {
                if (userRoleVo.getSortOrder().equals("desc"))
                    queryWrapper.orderByDesc(userRoleVo.getSort());
                else
                    queryWrapper.orderByAsc(userRoleVo.getSort());
            }

            List<UserRoleVo> userRoleVos = userRolesService.selectUserRoleList(queryWrapper,
                    new Page<>(userRoleVo.getPageIndex(), userRoleVo.getPageSize()));

            IntStream.range(0, userRoleVos.size()).forEach(i -> {
                UserRoleVo model = userRoleVos.get(i);
                if (model.getParentID() != null) {
                    List<UserRoleVo> filerList = userRoleVos.stream().filter(f -> f.getUserID() == model.getParentID()).collect(Collectors.toList());
                    if (filerList.size() > 0)
                        userRoleVos.get(i).setParentName(filerList.get(0).getUserName());
                }
            });

            //得到当前菜单具备的功能权限
            List<Button> list = permissionService.filterPermission(String.valueOf(userRoleVo.getRoleID()), menuId);
            userRoleVos.forEach(model -> model.setButtonList(list));

            returnVO.setTotal(total);
            returnVO.setData(userRoleVos);
            return returnVO;

        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }*/

    @PostMapping("/changeState")
    @ResponseBody
    @AuthToken
    public ReturnVO changeState(@RequestBody Users users) {
        try {
            Users model = new Users();
            model=userService.getById(users.getUserID());
            model.setActivity(users.getActivity());
            QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
            usersQueryWrapper.eq("userID", users.getUserID());
            userService.update(model, usersQueryWrapper);
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    @PostMapping("/edit")
    @ResponseBody
    @AuthToken
    public ReturnVO edit(@RequestBody UserRoleVo userRoleVo) {
        try {
            Users users = new Users();
            users=userService.getById(userRoleVo.getUserID());
            users.setWeixinpay(userRoleVo.getWeixinpay());
            users.setUserType(userRoleVo.getRoleID());
            users.setUserName(userRoleVo.getUserName());
            users.setSex(userRoleVo.getSex());
            users.setPhone(userRoleVo.getPhone());
            users.setEmail(userRoleVo.getEmail());
            users.setBankUserName(userRoleVo.getBankUserName());
            users.setBankNo(userRoleVo.getBankNo());
            users.setBankName(userRoleVo.getBankName());
            users.setAlipay(userRoleVo.getAlipay());
            users.setAmount(userRoleVo.getAmount());
            users.setActivity(userRoleVo.getActivity());
            users.setUserID(userRoleVo.getUserID());

            QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
            usersQueryWrapper.eq("userID", userRoleVo.getUserID());
            userService.update(users, usersQueryWrapper);

            UserRoles userRoles = new UserRoles();
            userRoles.setUserID(userRoleVo.getUserID());
            userRoles.setRoleID(userRoleVo.getRoleID());
            QueryWrapper<UserRoles> userRolesQueryWrapper = new QueryWrapper<>();
            userRolesQueryWrapper.eq("userID", userRoleVo.getUserID());
            userRolesService.update(userRoles, userRolesQueryWrapper);
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /**
     * 默认创建下一个角色，当前用户不允许创建当前角色或越级别创建
     * 例如超级管理员创建的用户只能是管理员
     * 管理员创建的用户只能是总代理，依此类推
     * <p>
     * 创建用户时，菜单可以选择，功能按钮沿用当前角色的默认权限，需要修改，可以去菜单管理进行修改
     *
     * @param userRoleVo
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    @AuthToken
    public ReturnVO add(@RequestBody UserRoleVo userRoleVo) {
        try {

            //存在下级角色，允许新增用户,开启事务，失败回滚
            userService.CreateUser(userRoleVo);

            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    @PostMapping("/addInit")
    @ResponseBody
    @AuthToken
    public ReturnVO addInit(@RequestBody RoleMenuVo roleMenuVo) {
        try {
            QueryWrapper<RoleMenuVo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("r.roleID", roleMenuVo.getRoleID());
            List<RoleMenuVo> roleMenuVos = roleMenuService.selectRoleMenuList(queryWrapper, null);

            List<RoleMenuVo> listLevel2 = roleMenuVos.stream().filter(f -> f.getLevel().equals("2")).collect(Collectors.toList());
            List<RoleMenuVo> listIndex = roleMenuVos.stream().filter(f -> f.getId() == 1).collect(Collectors.toList());

            List<Menu> listMenu = new ArrayList<>();
            menuList(listLevel2, listMenu);
            menuList(listIndex, listMenu);

            return new ReturnVO(listMenu);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    private void menuList(List<RoleMenuVo> listIndex, List<Menu> listMenu) {
        for (RoleMenuVo rv1 : listIndex
        ) {
            Menu menu = new Menu();
            menu.setId(rv1.getId());
            menu.setUrl(rv1.getUrl());
            menu.setTextCH(rv1.getTextCH());
            menu.setLevel(rv1.getLevel());
            menu.setParentID(rv1.getParentID());
            menu.setOrderID(rv1.getOrderID());
            menu.setImageUrl(rv1.getImageUrl());
            menu.setKeyName(rv1.getKeyName());

            listMenu.add(menu);
        }
    }
    //获取用户子集权限
    public List<Integer> idList(@RequestParam(value = "userId",required = false) Integer userId){
        List<Integer> idListTotal=new ArrayList<>();
        List<Integer> idList=new ArrayList<>();
        idListTotal.add(userId);
        List<Users> users1=new ArrayList<>();
        List<Users> users2=new ArrayList<>();
        QueryWrapper<Users> wrapper1 =new QueryWrapper<Users>();
        wrapper1.eq("parentID",userId);
        users1=userService.getBaseMapper().selectList(wrapper1);
        for(Users users:users1){
            idListTotal.add(users.getUserID());
            idList.add(users.getUserID());
        }
        for(Integer user:idList){
            QueryWrapper<Users> wrapper2 =new QueryWrapper<Users>();
            wrapper2.eq("parentID",user);
            users2=userService.getBaseMapper().selectList(wrapper2);
            for(Users users3:users2){
                idListTotal.add(users3.getUserID());
            }
        }
        return idListTotal;
    }
}
